import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs';
import {tap} from 'rxjs/operators';

import {CacheService} from '@kylin/cache';
import {RouterService} from '@kylin/router';
import {NzMessageService} from 'ng-zorro-antd';


@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
    constructor(private routerService: RouterService,
                private nzMessageService: NzMessageService,
                private cacheService: CacheService) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req).pipe(
            tap(
                event => {
                    if (event instanceof HttpResponse) {
                        if (event.status === 200) {
                            this.responseErrorHandler(event.body);
                        }
                    }
                },
                error => {
                    this.responseErrorHandler('登录已过期，请重新登录');
                }
            )
        );
    }

    /**
     *
     * @param status 此参数为后端HTTP返回的错误类型 200为正常
     */
    private responseErrorHandler(body) {
        switch (body.message) {
            case '登录已过期，请重新登录':
                this.nzMessageService.warning('登录已过期，请重新登录!');
                this.cacheService.remove('token');
                this.routerService.navigate('/login');
                break;
            default:
                console.log('default');
        }
    }
}
